<?php

namespace app\api\model;

use think\Model;
use traits\model\SoftDelete;

class Friends extends Model
{
    use SoftDelete;
    protected $autoWriteTimestamp = "int";
    protected $deleteTime = "deletetime";
    protected $createTime = "createtime";
    protected $updateTime = "updatetime";

    protected $hidden = ['status', 'deletetime', 'createtime', 'updatetime'];

    public static function getFriendByUser($phone)
    {
        return self::with(['relations'])->where('phone', $phone)->find();
    }

    public function user()
    {
        return $this->hasOne(Users::class, 'id', 'user_id');
    }

    public function relations()
    {
        return $this->hasOne(Relation::class, "id", "relation_id");
    }

    public static function getFriendsByParent($parent_id)
    {
        return self::with(['user', 'relations'])->where('parent_id', $parent_id)->select();
    }

    public static function add($parent_id, array $data)
    {
        $studentIds = ParentStudents::getStudentIds($parent_id);
        foreach ($studentIds as $val) {
            $data['parent_id'] = $parent_id;
            $data['student_id'] = $val;
            $data['createtime'] = time();
            $data['updatetime'] = time();
            $arr[] = $data;
        }
        return self::insertAll($arr);
    }

    public function edit(array $data)
    {
        return $this->allowField(true)->save($data);
    }

    public static function getFriendCounts($parent_id)
    {
        return self::whereIn('parent_id', $parent_id)->count();
    }

    public static function getFriendsBystudent($student_id)
    {
        $friends_ids = self::getFriendIds($student_id);
        return self::with(['user', 'relations'])->whereIn('id', $friends_ids)->select();
    }

    /**
     * 亲友去重
     * @param $student_id
     * @return array|bool|string
     */
    public static function getFriendIds($student_id)
    {
        $parent_ids = Students::getParentIds($student_id);
        $friends_id = self::whereIn('parent_id', $parent_ids)->column('id');
        return array_unique($friends_id);
    }

    public static function getByUserId($user_id)
    {
        return self::with(['user', 'relations'])->where('user_id', $user_id)->find();
    }
}
